#! -*- coding:utf-8 -*-
from datetime import timedelta
from common.lottery import METIS_GAME_TYPE
from common.stats import MG_BIGBANG_COLL as mg
from common.utils.tz import utc_to_local

METIS_GAME_WITH_BANKER = [
    METIS_GAME_TYPE.SUPER_BULL,
    METIS_GAME_TYPE.DRAGON_TIGER,
    METIS_GAME_TYPE.FLOWER
]


def create_metis_report(day, new_user_list):
    result = {}
    for game_id in METIS_GAME_TYPE.values():
        result[str(game_id)] = _cal_game_daily_data(game_id, day, new_user_list)

    mg.metis_report.update_one(
        {'_id': utc_to_local(day).strftime('%Y-%m-%d')},
        {'$set': result}, upsert=True)


def _cal_game_daily_data(game_id, day, new_user_list):
    end = day + timedelta(days=1)
    updated_filter = {'$gte': day, '$lt': end}
    result = dict()

    bet_key = 'metis.{}_bet_amount'.format(game_id)
    profit_key = 'metis.{}_total_profit'.format(game_id)

    # 统计投注用户人数
    result['user_count'] = mg.daily_stats.count({
        'updated_at': updated_filter, bet_key: {'$exists': 1}}) or 0

    for key in ['_', 'new_user']:
        data = {}
        match = {
            'updated_at': updated_filter,
             bet_key: {'$exists': True}
        }
        if key == 'new_user':
            match['user_id'] = {'$in': new_user_list}
        group = {
            '_id': None,
            'user_count': {'$push': '$user_id'},
            'total_bet': {'$sum': '$' + bet_key},
            'total_profit': {'$sum': '$' + profit_key},
            'gain_amount': {'$sum': {
                "$switch": {
                    "branches": [
                        {
                            "case": {
                                "$gt": ['$' + profit_key, 0]
                            },
                            "then": '$' + profit_key
                        }
                    ], "default": 0}
            }},
            'gain_count': {'$push': {
                "$switch": {
                    "branches": [
                        {
                            "case": {
                                "$gt": ['$' + profit_key, 0]
                            },
                            "then": '$user_id'
                        }
                    ], "default": None}
            }},
            'lose_amount': {'$sum': {
                "$switch": {
                    "branches": [
                        {
                            "case": {
                                "$lt": ['$' + profit_key, 0]
                            },
                            "then": '$' + profit_key
                        }
                    ], "default": 0}
            }},
            'lose_count': {'$push': {
                "$switch": {
                    "branches": [
                        {
                            "case": {
                                "$lt": ['$' + profit_key, 0]
                            },
                            "then": '$user_id'
                        }
                    ], "default": None}
            }},
            'banker_person': {'$push': {
                "$switch": {
                    "branches": [
                        {
                            "case": {
                                "$gt": ['$metis.banker.{}_is_banker', 0]
                            },
                            "then": '$user_id'
                        }
                    ], "default": None}
            }},
            'banker_bet': {'$sum': '$metis.banker.{}_banker_total_bet'.format(game_id)},
            'banker_gain': {'$sum': '$metis.banker.{}_banker_bet_result'.format(game_id)},
            'banker_count': {'$sum': '$metis.banker.{}_banker_count'.format(game_id)}
        }

        t = mg.daily_stats.aggregate([
            {'$match': match},
            {'$group': group}
        ])
        t = t.next() if t.alive else {}

        data['user_count'] = t.get('user_count', [])
        data['total_bet'] = t.get('total_bet', 0)
        data['total_profit'] = -1 * t.get('total_profit', 0)
        data['gain_amount'] = t.get('gain_amount', 0)
        data['gain_count'] = t.get('gain_count', [])
        data['lose_amount'] = t.get('lose_amount', 0)
        data['lose_count'] = t.get('lose_count', [])
        if game_id in METIS_GAME_WITH_BANKER:
            data['banker_person'] = t.get('banker_person', [])
            data['banker_bet'] = t.get('banker_bet', 0)
            data['banker_count'] = t.get('banker_count', 0)
            data['banker_gain'] = t.get('banker_gain', 0)
        for count_type in ['gain_count', 'lose_count', 'user_count', 'banker_person']:
            if count_type in data:
                data[count_type] = [x for x in data[count_type] if x is not None]
        if key == 'new_user':
            result['new_user'] = data
        else:
            result.update(data)
    return result
